package com.chart.common.utils.sms;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.redis.RedisCache;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author tianyh
 * @Description:普通短信发送
 */
public class SmsSendUtils {

    public static final String qcode = "手机号：";

    public static final String charset = "utf-8";
    //老的
    // 用户平台API账号(非登录账号,示例:N1234567)
//    public static String account = "N2515324";
//    // 用户平台API密码(非登录密码)
//    public static String password = "0JxzcSwDF2fa24";

    //新的
//    public static String account = "YZM2216127";
//    // 用户平台API密码(非登录密码)
//    public static String password = "70R875Ys11643d";

//    N8798273
//    Hzchipshare203!

    public static String account = "N8798273";
    // 用户平台API密码(非登录密码)
    public static String password = "Hzchipshare203!";


    public static AjaxResult sendSms(String phoneNum, RedisCache redisCache) throws UnsupportedEncodingException {
        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
        String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";

        // 短信内容
        String code = getCode();
        String msg = "【TOPCHARTS】尊敬的用户，您的验证码为" + code + "，3分钟内有效，请不要把验证码泄露给他人";
        //状态报告
        String report = "true";

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phoneNum, report);

        String requestJson = JSON.toJSONString(smsSingleRequest);
        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);


        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        if (smsSingleResponse.getCode().equals("0")) {
            redisCache.setCacheObject(qcode + phoneNum, code, 3, TimeUnit.MINUTES);
            return AjaxResult.success(code);
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String errorMsg = JSON.toJSONString(jsonObject.get("errorMsg"));
        return AjaxResult.error(errorMsg);
    }


//    public static AjaxResult sendSms(String phoneNum, RedisCache redisCache) throws UnsupportedEncodingException {
//        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
//         String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";
//        //String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/encrypt/json";
//        //https://smssh1.253.com/msgv1/send/encrypt/json
//        // 短信内容
//        String code = getCode();
//        String msg = "【TOPCHARTS】尊敬的用户，您的验证码为" + code + "，3分钟内有效，请不要把验证码泄露给他人";
//        //状态报告
//        String report = "true";
//
//        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phoneNum, report);
//
//        String requestJson = JSON.toJSONString(smsSingleRequest);
//
////        System.out.println("before request string is: " + requestJson);
//
//        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
//
////        System.out.println("response after request result is :" + response);
//
//        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
//
////        System.out.println("response  toString is :" + smsSingleResponse);
//        if (smsSingleResponse.getCode().equals("0")) {
//            redisCache.setCacheObject(qcode + phoneNum, code, 3, TimeUnit.MINUTES);
//            return AjaxResult.success(code);
//        }
//        JSONObject jsonObject = JSONObject.parseObject(response);
//        String errorMsg = JSON.toJSONString(jsonObject.get("errorMsg"));
//        return AjaxResult.error(errorMsg);
//    }


//    为降低 AccessKey 泄露的风险，自 2023 年 7 月 5 日起，新建的主账号 AccessKey 只在创建时提供 Secret，后续不可再进行查询，请保存好Secret。
//    AccessKey ID
//    LTAI5tCsxiEg348wiJfwWEit
//
//    AccessKey Secret
//4qCJxAgvLOr1kCTsjF7h4aA57lIxJt


    //公司测试
//    public static String accessKeyId = "LTAI5tCsxiEg348wiJfwWEit";
//    public static String accessKeySecret = "4qCJxAgvLOr1kCTsjF7h4aA57lIxJt";
//    public static String signName = "阿里云短信测试";
//    public static String templateCode = "SMS_154950909";


    //公司
    public static String accessKeyId = "LTAI5tA8Ny3CaNbBaHsVK6em";
    public static String accessKeySecret = "bdG45Yn5d60xNx5s3ecYnDMGrTrBA3";
    public static String signName = "智图小易司";

    public static String templateCode = "SMS_473335182";


    // 静态方法：发送短信
    public static AjaxResult sendSmsAli(String phoneNumber, RedisCache redisCache) throws Exception {

        // 生成验证码
        String code = getCode();

        // 短信内容使用阿里云模板规范，短信参数应该是 JSON 格式
        String templateParam = String.format("{\"code\":\"%s\"}", code);

        // 创建短信客户端
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);

        // 构建短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(templateParam);

        // 运行时配置
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 发送短信
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("短信发送成功" + code);

            // 将验证码存入 Redis，3 分钟过期
            redisCache.setCacheObject(qcode + phoneNumber, code, 3, TimeUnit.MINUTES);

            // 返回成功的 AjaxResult
            return AjaxResult.success(code);

        } catch (Exception error) {
            // 处理发送失败的异常
            System.err.println("短信发送失败：" + error.getMessage());
            return AjaxResult.error("短信发送失败：" + error.getMessage());
        }
    }

    public static String getCode() {
        Random random = new Random();
        int min = 100000; // 最小值为100000
        int max = 999999; // 最大值为999999
        int randomNumber = random.nextInt(max - min + 1) + min;
        return String.valueOf(randomNumber);
    }


//        // 用户平台账号
//        public static String account = "N8798273";
//        // 用户平台API密码(非登录密码)
//        public static String password = "Hzchipshare203!";


    /**
     * 如果创蓝响应出现错误信息 自动切换阿里短信验证码
     * 同时给管理员发送一条消息
     * 最后再把这个手机号通过阿里补发一条短信
     *
     * @return AjaxResult 发送结果
     */
    public static AjaxResult sendSmsWithFallback(String phoneNum, RedisCache redisCache) {
        AjaxResult ajaxResult;
        try {
            // 尝试使用创蓝发送短信
            ajaxResult = sendSmsUsingChuanglan(phoneNum, redisCache);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return AjaxResult.error("发送短信失败，编码不支持: " + e.getMessage());
        }

        // 如果创蓝发送失败，则切换到阿里云
        if (!ajaxResult.isSuccess()) {
            // 提取创蓝发送短信时的错误信息并通知管理员
            String errorMessage = (String) ajaxResult.get(AjaxResult.MSG_TAG);
            notifyAdmin(redisCache); // 使用 get("msg") 获取错误信息

            try {
                // 尝试使用阿里云发送短信
                ajaxResult = sendSmsUsingAliyun(phoneNum, redisCache);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("阿里云短信发送失败: " + e.getMessage());
            }
        }

        return ajaxResult.isSuccess() ? AjaxResult.success() : ajaxResult;
    }


    /**
     * 使用创蓝发送短信
     *
     * @param phoneNum   发送短信的手机号
     * @param redisCache Redis缓存对象
     * @return AjaxResult 发送结果
     * @throws UnsupportedEncodingException 可能出现的编码异常
     */
    private static AjaxResult sendSmsUsingChuanglan(String phoneNum, RedisCache redisCache) throws UnsupportedEncodingException {
        String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";
        // 短信内容
        String code = getCode();
        String msg = "【TOPCHARTS】尊敬的用户，您的验证码为" + code + "，3分钟内有效，请不要把验证码泄露给他人";
        // 状态报告
        String report = "true";

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phoneNum, report);
        String requestJson = JSON.toJSONString(smsSingleRequest);
        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        // 处理发送结果
        if ("0".equals(smsSingleResponse.getCode())) {
            redisCache.setCacheObject(qcode + phoneNum, code, 3, TimeUnit.MINUTES);
            return AjaxResult.success(code);
        }

        // 处理错误信息
        JSONObject jsonObject = JSON.parseObject(response);
        String errorMsg = jsonObject.getString("errorMsg");
        return AjaxResult.error(errorMsg);
    }

    /**
     * 使用阿里云发送短信
     *
     * @param phoneNumber 发送短信的手机号
     * @param redisCache  Redis缓存对象
     * @return AjaxResult 发送结果
     * @throws Exception 可能出现的异常
     */
    private static AjaxResult sendSmsUsingAliyun(String phoneNumber, RedisCache redisCache) throws Exception {
        // 生成验证码
        String code = getCode();

        // 短信内容使用阿里云模板规范，短信参数应该是 JSON 格式
        String templateParam = String.format("{\"code\":\"%s\"}", code);

        // 创建短信客户端
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);

        // 构建短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(templateParam);

        // 运行时配置
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 发送短信
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("短信发送成功" + code);

            // 将验证码存入 Redis，3 分钟过期
            redisCache.setCacheObject(qcode + phoneNumber, code, 3, TimeUnit.MINUTES);

            // 返回成功的 AjaxResult
            return AjaxResult.success(code);

        } catch (Exception error) {
            // 处理发送失败的异常
            System.err.println("短信发送失败：" + error.getMessage());
            return AjaxResult.error("短信发送失败：" + error.getMessage());
        }
    }

    /**
     * 通知管理员
     *
     * @param
     */
    private static void notifyAdmin(RedisCache redisCache) {
        // 尝试创蓝发送通知短信
        try {
            // 发送短信
            AjaxResult ajaxResult = sendSmsUsingChuanglans(redisCache);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送通知短信给管理员失败: " + e.getMessage());
        }
    }



    private static AjaxResult sendSmsUsingChuanglans(RedisCache redisCache) throws UnsupportedEncodingException {
        String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";
        // 管理员的手机号数组
        String[] phoneNums = {"17681865727", "15858110257"}; // 替换为你的管理员手机号
        String message = "创蓝短信验证码错误已自动切换到阿里";
        // 状态报告
        String report = "true";
        // 生成验证码
        String code = getCode();
        // 用于存储发送结果
        boolean allSuccess = true; // 标记是否所有发送成功
        StringBuilder errorMessages = new StringBuilder(); // 存储错误信息

        for (String phoneNum : phoneNums) {
            SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, message, phoneNum, report);
            String requestJson = JSON.toJSONString(smsSingleRequest);
            String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
            SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

            // 处理发送结果
            if ("0".equals(smsSingleResponse.getCode())) {
                // 如果发送成功，将验证码存入 Redis
                redisCache.setCacheObject(qcode + phoneNum, code, 3, TimeUnit.MINUTES);
            } else {
                // 记录错误信息
                JSONObject jsonObject = JSON.parseObject(response);
                String errorMsg = jsonObject.getString("errorMsg");
                errorMessages.append("手机号: ").append(phoneNum).append("，错误信息: ").append(errorMsg).append("\n");
                allSuccess = false; // 标记有发送失败
            }
        }

        // 检查是否所有发送都成功
        if (allSuccess) {
            return AjaxResult.success(code); // 所有发送成功，返回成功状态
        } else {
            return AjaxResult.error("发送失败，详细信息:\n" + errorMessages.toString()); // 返回失败信息
        }
    }


}
